import { DialogRef, useDialog } from "../../../../utils/react-use/useDialog";
import { Icon, Modal, message } from "tea-component";
import React, { useState } from "react";
import { FormValue } from "./CreateGroupForm";
import { Form, Input, Button, Checkbox } from "tea-component";
import { sendMsg, createGroup, joinGroup } from "../../../../api";
import { useSettingConfig } from "../../../../utils/react-use/useSettingConfig";
import Toast from "../../../../components/toast/Toast";
import "./create-group-form.scss";
import { Avatar } from "../../../../components/avatar/avatar";

export interface SearchGroupRecordType {
  userId: string;
}

export const SearchGroupDialog = (props: { onSuccess?: () => void;
    dialogRef: DialogRef<SearchGroupRecordType>;}): JSX.Element => {
  const { onSuccess, dialogRef } = props;
  const { userId} = useSettingConfig();
  const [serchVal,setSerchVal] = useState("");
  const [searInf,setSearInf] = useState("输入群号后搜索");
  const [groupid,setGroupid] = useState("");
  const [isAllowin,setIsAllowin] = useState(false);

  const [visible, setShowState, defaultForm] = useDialog<SearchGroupRecordType>(
    dialogRef,
    {}
  );
  const onClose = () => setShowState(false);
  const success = () => {
    onSuccess();
    onClose();
  };

  const onSubmit = async (formData: FormValue) => {
    const res = await createGroup(formData);
    const currentGroupId = res.create_group_result_groupid;
    await sendMsg({
      convId: currentGroupId,
      convType: 2,
      messageElementArray: [
        {
          elem_type: 5,
          custom_elem_data: JSON.stringify({
            businessID: "group_create", content: "创建群组",opUser: userId, version: 4,
          }),
        },
      ],
      userId: userId,
    });
  };
  const validateOldValue = async (value: string, label: string) => {
    if (!value) {
      return `${label}必填`;
    }
  };
  const setValue = async (value) => {
      setSerchVal(value);
  };
  const hanleJoin = async () => {
    if(groupid.length <1) return;
    const param ={groupId:groupid}
    const data = await joinGroup(param);
    if(data.code==10013){
      message.warning({style:{top:"50%"},content: '您已经加入该群!!'});
    }else if(data.code==0){
      message.success({style:{top:"50%"},content: '申请成功'});
      setSerchVal("");
      setIsAllowin(false);
      onSuccess();
      onClose();
    }else{
      message.error({style:{top:"50%"},content: '申请出错:'+data.desc});
    }
    console.log(data);
  }
  const hanleSearch =  () => {
    if(serchVal.length<1) return;
    const request = require('request')
    setGroupid("");
    request.get(Toast.defaultser+'/api/app/group/'+serchVal, {
        headers: {
            Authorization: Toast.token,
        },
    }, (error, res) => {
        if (error) {
            console.error(error)
            return
        }
        let body = JSON.parse(res.body);
        if(body.code==200&& body.data){
          setGroupid(body.data.imGroupId);
          setSearInf(body.data.name);
          setIsAllowin(true);
        }else{
          setSearInf(body.message+" code:"+ body.code);
          setIsAllowin(false);
        }
            
    });
  };
  return (
    <Modal  className="dialog"  disableEscape  visible={visible} onClose={onClose}  caption="搜索群">
      <Modal.Body>
            <div className="search-box">
              <Icon type="search" className="search-icon" />
              <Input type="search" className="search-input" value={serchVal}  placeholder="查找群成员" onChange={setValue}/>
              <Button className="btn" type="primary" htmlType="submit"  onClick={hanleSearch}>
                搜索
              </Button>
            </div>
            <div className="searchResult">
              { 
                groupid.length >0 ? <Avatar nickName= {searInf} />:null 
              }
               <span> {searInf} </span>
            </div>
            <div className="searchBottom">
              <Button className="btn" type="primary" htmlType="button" disabled={!isAllowin} onClick={hanleJoin} >
                申请加入
              </Button>
              <Button className="btn" onClick={(e) => {
                  e.stopPropagation(); e.preventDefault();
                  onClose();
                }}>
                取消
              </Button>
            </div>
      </Modal.Body>
    </Modal>
  );
};
